package indi.luckly.config.shiro;

import indi.luckly.config.shiro.token.SecureToken;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.AuthenticatingFilter;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Slf4j
public class TokenFilter extends AuthenticatingFilter {

    private static final String X_TOKEN = "X-Token";

    //  private ITokenService tokenService = null;

    /**
     * 创建Token, 支持自定义Token
     */
    @Override
    protected AuthenticationToken createToken(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
        String token = this.getToken((HttpServletRequest) servletRequest);
        if (ObjectUtils.isEmpty(token)) {
            log.error("token is empty");
            return null;
        }
        return new SecureToken(token);
    }

    /**
     * 兼容跨域
     */
    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
        return ((HttpServletRequest) request).getMethod().equals(RequestMethod.OPTIONS.name());
    }

    @Override
    protected boolean onAccessDenied(ServletRequest servletRequest, ServletResponse servletResponse) throws Exception {
//        return super.onAccessDenied(servletRequest,servletResponse);
//        HttpServletRequest request = (HttpServletRequest)servletRequest;
//        HttpServletResponse response = (HttpServletResponse) servletResponse;
//
//        String token = this.getToken(request);
//        if(ObjectUtils.isEmpty(token)){
//            this.respUnLogin(request, response);
//            return false;
//        }
//
//        // 校验Token的有效性
//        if(tokenService == null){
//            tokenService = SpringContext.getBean(ITokenService.class);
//        }
//
//        if(!tokenService.check(token)){
//            this.respUnLogin(request, response);
//        }

        // 根据token获取用户信息，会执行 TokenRealm#doGetAuthenticationInfo 方法
        return executeLogin(servletRequest, servletResponse);
    }

//    private void respUnLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
//        response.setContentType("application/json;charset=utf-8");
//        response.setHeader("Access-Control-Allow-Credentials", "true");
//        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
//
//        Response resp = new Response(BusinessCodeEnum.USER_UN_LOGIN.getCode(), BusinessCodeEnum.USER_UN_LOGIN.getMsg());
//        response.getWriter().print(JSONUtil.toJsonStr(resp));
//    }

    /**
     * 获取token
     * 优先从header获取
     * 如果没有，则从parameter获取
     *
     * @param request request
     * @return token
     */
    private String getToken(HttpServletRequest request) {
        String token = request.getHeader(X_TOKEN);
        if (ObjectUtils.isEmpty(token)) {
            token = request.getParameter(X_TOKEN);
        }
        return token;
    }
}
